package com.hmdp.service.impl;

import cn.hutool.core.lang.UUID;
import com.hmdp.service.ILock;
import lombok.Builder;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName SimpleRedisLock
 * @Description TODO
 * @Author daoketa
 * @Version 1.0
 * 不可重入 redis 分布式锁
 **/

public class SimpleRedisLock implements ILock {

    // 负责执行 lua 脚本，ctrl+h 查看类的继承结构
    private static final DefaultRedisScript<Long> DEFAULT_REDIS_SCRIPT;

    // 初始化 lua 脚本类
    static {
        DEFAULT_REDIS_SCRIPT = new DefaultRedisScript<>();
        DEFAULT_REDIS_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        DEFAULT_REDIS_SCRIPT.setResultType(Long.class);
    }

    // key 前缀
    private static final String KEY_PREFIX = "lock:";

    // value 前缀
    private static final String THREAD_PREFIX = UUID.randomUUID().toString(true) +"-";

    // key 自定义参数前缀
    private final String name;

    private final StringRedisTemplate stringRedisTemplate;

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name){
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        // 获取线程标识
        String threadID = THREAD_PREFIX + Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + this.name,
                threadID, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    /**
     * 当前线程标识与 redis 里锁的线程标识对比,属于自己线程的锁则释放锁，不是则忽略
     * 存在原子性问题
     * 判断和删除锁时两条命令，可能判断成功后，准备删除锁，却在 JVM 里阻塞导致锁过期，阻塞结束后将会误删别的线程的锁
     * */
    public void unLock() {
        String threadID = THREAD_PREFIX + Thread.currentThread().getId();
        String redisThreadId = stringRedisTemplate.opsForValue().get(KEY_PREFIX + this.name);
        if (threadID.equals(redisThreadId)){
            //通过del删除锁
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }
    }

    @Override
    /**
     * Lua 脚本释放锁
     * */
    public void LuaUnLock() {
        // 调用 lua 脚本
        stringRedisTemplate.execute(DEFAULT_REDIS_SCRIPT,
                                    Collections.singletonList(KEY_PREFIX + name),   // 快捷创建单个元素的集合List
                                    THREAD_PREFIX + Thread.currentThread().getId());
    }
}
